package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Entry.ShiftTime;
import com.example.chamberlainserver.Service.ShiftTimeService;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import com.example.chamberlainserver.dto.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 班次时间控制器
 */
@RestController
@RequestMapping("/schedule/shifts")
public class ShiftTimeController {

    @Autowired
    private ShiftTimeService shiftTimeService;

    /**
     * 添加班次时间
     */
    @PostMapping("/add")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> addShiftTime(@RequestBody ShiftTime shiftTime) {
        try {
            // 设置创建人
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            // 这里需要根据username获取userId，暂时设置为1
            shiftTime.setCreatedBy(1);
            
            boolean success = shiftTimeService.addShiftTime(shiftTime);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("添加班次时间成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("添加班次时间失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("添加班次时间失败: " + e.getMessage()));
        }
    }

    /**
     * 根据ID获取班次时间
     */
    @GetMapping("/get/{id}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<ShiftTime>> getShiftTimeById(@PathVariable String id) {
        try {
            ShiftTime shiftTime = shiftTimeService.getShiftTimeById(id);
            
            if (shiftTime != null) {
                return ResponseEntity.ok(ApiResponse.success("获取班次时间成功", shiftTime));
            } else {
                return ResponseEntity.ok(ApiResponse.error(404, "班次时间不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取班次时间失败: " + e.getMessage()));
        }
    }

    /**
     * 根据类型获取班次时间列表
     */
    @GetMapping("/type/{shiftType}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<ShiftTime>>> getShiftTimesByType(@PathVariable String shiftType) {
        try {
            List<ShiftTime> shiftTimes = shiftTimeService.getShiftTimesByType(shiftType);
            return ResponseEntity.ok(ApiResponse.success("获取班次时间列表成功", shiftTimes));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取班次时间列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取所有活跃的班次时间
     */
    @GetMapping("/active")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<ShiftTime>>> getActiveShiftTimes() {
        try {
            List<ShiftTime> shiftTimes = shiftTimeService.getActiveShiftTimes();
            return ResponseEntity.ok(ApiResponse.success("获取活跃班次时间列表成功", shiftTimes));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取活跃班次时间列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取所有班次时间
     */
    @GetMapping("/all")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<ShiftTime>>> getAllShiftTimes() {
        try {
            List<ShiftTime> shiftTimes = shiftTimeService.getAllShiftTimes();
            return ResponseEntity.ok(ApiResponse.success("获取所有班次时间列表成功", shiftTimes));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取所有班次时间列表失败: " + e.getMessage()));
        }
    }

    /**
     * 更新班次时间
     */
    @PutMapping("/update")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> updateShiftTime(@RequestBody ShiftTime shiftTime) {
        try {
            boolean success = shiftTimeService.updateShiftTime(shiftTime);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("更新班次时间成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("更新班次时间失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新班次时间失败: " + e.getMessage()));
        }
    }

    /**
     * 删除班次时间
     */
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deleteShiftTime(@PathVariable String id) {
        try {
            boolean success = shiftTimeService.deleteShiftTime(id);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("删除班次时间成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("删除班次时间失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除班次时间失败: " + e.getMessage()));
        }
    }

    /**
     * 启用/禁用班次时间
     */
    @PutMapping("/status/{id}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> updateShiftTimeStatus(
            @PathVariable String id,
            @RequestParam Boolean isActive) {
        try {
            boolean success = shiftTimeService.updateShiftTimeStatus(id, isActive);
            
            if (success) {
                String action = isActive ? "启用" : "禁用";
                return ResponseEntity.ok(ApiResponse.success(action + "班次时间成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("更新班次时间状态失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新班次时间状态失败: " + e.getMessage()));
        }
    }

    /**
     * 分页查询班次时间列表
     */
    @GetMapping("/pagedList")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<PageResult<ShiftTime>>> getPagedShiftTimeList(
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "shiftName", required = false) String shiftName,
            @RequestParam(value = "shiftType", required = false) String shiftType,
            @RequestParam(value = "isActive", required = false) Boolean isActive,
            @RequestParam(value = "createdBy", required = false) Integer createdBy) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("current", current);
            params.put("pageSize", pageSize);
            params.put("offset", (current - 1) * pageSize);
            
            if (shiftName != null && !shiftName.trim().isEmpty()) {
                params.put("shiftName", shiftName.trim());
            }
            if (shiftType != null && !shiftType.trim().isEmpty()) {
                params.put("shiftType", shiftType.trim());
            }
            if (isActive != null) {
                params.put("isActive", isActive);
            }
            if (createdBy != null) {
                params.put("createdBy", createdBy);
            }
            
            PageResult<ShiftTime> pageResult = shiftTimeService.getPagedShiftTimeList(params);
            return ResponseEntity.ok(ApiResponse.success("获取班次时间列表成功", pageResult));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取班次时间列表失败: " + e.getMessage()));
        }
    }

    /**
     * 验证班次时间配置
     */
    @PostMapping("/validate")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Boolean>> validateShiftTime(@RequestBody ShiftTime shiftTime) {
        try {
            boolean isValid = shiftTimeService.validateShiftTimeConfig(shiftTime);
            
            if (isValid) {
                return ResponseEntity.ok(ApiResponse.success("班次时间配置验证通过", true));
            } else {
                return ResponseEntity.ok(ApiResponse.success("班次时间配置验证失败", false));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("验证班次时间配置失败: " + e.getMessage()));
        }
    }
}